package br.com.sig.cadastro.produto.presentation.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Observes;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import br.com.sig.business.exception.BaseException;
import br.com.sig.cadastro.produto.business.model.bo.ImagemBO;
import br.com.sig.cadastro.produto.business.model.entity.Imagem;
import br.com.sig.presentation.event.UploadedImagemEvent;

@Named
@SessionScoped
public class ImageAction implements Serializable {

	private static final long serialVersionUID = -4308588832554192897L;
	
	private Imagem instance;
	private BufferedImage image;

	@Inject
	private ImagemBO imagemBO;
	
	public Imagem getInstance() {
		return instance;
	}	

	public void setInstance(Imagem instance) {
		this.instance = instance;
	}
	
	public int getHeight() {
		try {
			if (getInstance() != null) {
				this.image = ImageIO.read(new ByteArrayInputStream(getInstance().getFile()));
				return this.image.getHeight();
			}
		} catch (IOException | NullPointerException e) {
			e.printStackTrace();
		}
		
		return 0;
	}
	
	public int getWidth() {
		try {
			if (getInstance() != null) {
				this.image = ImageIO.read(new ByteArrayInputStream(getInstance().getFile()));
				return this.image.getWidth() + 24;
			}
		} catch (IOException | NullPointerException e) {
			e.printStackTrace();
		}
		
		return 0;
	}
	
	public void carregarImagem() {
		String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("imageId");
		
		if (id != null && !id.isEmpty()) {
			try {
				setInstance(imagemBO.find(new Long(id)));
			} catch (NumberFormatException | BaseException e) {
				e.printStackTrace();
			}
		}		
	}
	
	public void postUploaded(@Observes UploadedImagemEvent event) {
		this.instance = event.getFoto();
	}

	public StreamedContent getFoto() {
		FacesContext context = FacesContext.getCurrentInstance();		
		
		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			if (getInstance() != null) {
				DefaultStreamedContent defaultStreamedContent = new DefaultStreamedContent(new ByteArrayInputStream(getInstance().getFile()));
				setInstance(null);
				return defaultStreamedContent;
			}

			return new DefaultStreamedContent();
		}
	}
	
}